package com.example.dubboclient.controller;

import com.example.dubboapi.entity.Order;
import com.example.dubboapi.entity.User;
import com.example.dubboapi.service.OrderService;
import com.example.dubboapi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 用户和订单控制器
 * 
 * 演示Dubbo消费者如何调用远程服务：
 * - @DubboReference 注解用于引用远程服务
 * - 支持集群容错、负载均衡、异步调用等特性
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class UserController {

    /**
     * 引用用户服务
     * 
     * DubboReference注解说明：
     * - interfaceClass: 指定服务接口
     * - version: 服务版本，必须与服务提供者版本匹配
     * - timeout: 超时时间
     * - retries: 重试次数
     * - loadbalance: 负载均衡策略
     * - check: 启动时是否检查服务存在
     */
    @DubboReference(
        interfaceClass = UserService.class,
        version = "1.0.0",
        timeout = 5000,
        retries = 2,
        loadbalance = "roundrobin",
        check = false
    )
    private UserService userService;

    /**
     * 引用订单服务
     */
    @DubboReference(
        interfaceClass = OrderService.class,
        version = "1.0.0",
        timeout = 3000,
        retries = 1,
        loadbalance = "leastactive",
        check = false
    )
    private OrderService orderService;

    // ========== 用户相关接口 ==========

    @PostMapping("/user")
    public User createUser(@RequestBody User user) {
        log.info("创建用户请求：{}", user);
        User result = userService.createUser(user);
        log.info("创建用户响应：{}", result);
        return result;
    }

    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable Long id) {
        log.info("查询用户请求，ID：{}", id);
        User user = userService.getUserById(id);
        log.info("查询用户响应：{}", user);
        return user;
    }

    @GetMapping("/user/username/{username}")
    public User getUserByUsername(@PathVariable String username) {
        log.info("根据用户名查询用户请求：{}", username);
        User user = userService.getUserByUsername(username);
        log.info("根据用户名查询用户响应：{}", user);
        return user;
    }

    @GetMapping("/user/email/{email}")
    public User getUserByEmail(@PathVariable String email) {
        log.info("根据邮箱查询用户请求：{}", email);
        User user = userService.getUserByEmail(email);
        log.info("根据邮箱查询用户响应：{}", user);
        return user;
    }

    @PutMapping("/user")
    public User updateUser(@RequestBody User user) {
        log.info("更新用户请求：{}", user);
        User result = userService.updateUser(user);
        log.info("更新用户响应：{}", result);
        return result;
    }

    @DeleteMapping("/user/{id}")
    public boolean deleteUser(@PathVariable Long id) {
        log.info("删除用户请求：{}", id);
        boolean result = userService.deleteUser(id);
        log.info("删除用户响应：{}", result);
        return result;
    }

    @GetMapping("/users")
    public List<User> getAllUsers() {
        log.info("获取所有用户列表请求");
        List<User> users = userService.getAllUsers();
        log.info("获取所有用户列表响应，数量：{}", users.size());
        return users;
    }

    // ========== 订单相关接口 ==========

    @PostMapping("/order")
    public Order createOrder(@RequestBody Order order) {
        log.info("创建订单请求：{}", order);
        Order result = orderService.createOrder(order);
        log.info("创建订单响应：{}", result);
        return result;
    }

    @GetMapping("/order/{id}")
    public Order getOrderById(@PathVariable Long id) {
        log.info("查询订单请求，ID：{}", id);
        Order order = orderService.getOrderById(id);
        log.info("查询订单响应：{}", order);
        return order;
    }

    @GetMapping("/order/no/{orderNo}")
    public Order getOrderByOrderNo(@PathVariable String orderNo) {
        log.info("根据订单编号查询订单请求：{}", orderNo);
        Order order = orderService.getOrderByOrderNo(orderNo);
        log.info("根据订单编号查询订单响应：{}", order);
        return order;
    }

    @GetMapping("/orders/user/{userId}")
    public List<Order> getOrdersByUserId(@PathVariable Long userId) {
        log.info("根据用户ID查询订单列表请求：{}", userId);
        List<Order> orders = orderService.getOrdersByUserId(userId);
        log.info("根据用户ID查询订单列表响应，数量：{}", orders.size());
        return orders;
    }

    @PutMapping("/order/{id}/status/{status}")
    public Order updateOrderStatus(@PathVariable Long id, @PathVariable Integer status) {
        log.info("更新订单状态请求，订单ID：{}，状态：{}", id, status);
        Order order = orderService.updateOrderStatus(id, status);
        log.info("更新订单状态响应：{}", order);
        return order;
    }

    @PutMapping("/order/{id}/cancel")
    public boolean cancelOrder(@PathVariable Long id) {
        log.info("取消订单请求：{}", id);
        boolean result = orderService.cancelOrder(id);
        log.info("取消订单响应：{}", result);
        return result;
    }

    // ========== 综合业务场景 ==========

    @PostMapping("/business/create-user-order")
    public String createUserAndOrder(@RequestParam String username, @RequestParam String email, 
                                   @RequestParam String phone, @RequestParam String productName, 
                                   @RequestParam BigDecimal amount) {
        log.info("创建用户和订单业务场景，用户名：{}，商品：{}，金额：{}", username, productName, amount);
        
        try {
            // 1. 创建用户
            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            user.setPhone(phone);
            User createdUser = userService.createUser(user);
            
            // 2. 创建订单
            Order order = new Order();
            order.setUserId(createdUser.getId());
            order.setProductName(productName);
            order.setAmount(amount);
            order.setRemark("用户：" + username + "购买商品：" + productName);
            Order createdOrder = orderService.createOrder(order);
            
            String result = String.format("业务处理成功！用户ID：%d，订单ID：%d，订单编号：%s", 
                    createdUser.getId(), createdOrder.getId(), createdOrder.getOrderNo());
            log.info(result);
            
            return result;
            
        } catch (Exception e) {
            log.error("创建用户和订单失败：", e);
            return "业务处理失败：" + e.getMessage();
        }
    }
}